package com.study;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Date;

/**
 * @Description: TODO
 * @Author: csc
 * @Date: 2024/4/17 11:11
 * @Version: 1.0
**/
public class influxdb {

    private static String createFluxQuery(String bucket, Date start, Date end, int pageNumber, int pageSize, String topic) {
        String startTime = DateUtil.format(start, "yyyy-MM-dd'T'HH:mm:ss'Z'");
        String endTime = DateUtil.format(end, "yyyy-MM-dd'T'HH:mm:ss'Z'");

        StringBuilder filterBuilder = new StringBuilder();
        if (StrUtil.isNotBlank(topic)) {
            //判断是否是其它类型的主题
            String resolvedTopic = resolveTopic(topic);
            if (resolvedTopic != null) {
                filterBuilder.append(" |> filter(fn: (r) => r[\"topic\"] == \"" + resolvedTopic + "\" )");
            }
        }

        return String.format(
                "from(bucket: \"%s\")\n" +
                        " |> range(start: %s, stop: %s)\n" +
                        " |> filter(fn: (r) => r[\"_measurement\"] == \"centreIotData\")\n" +
                        "%s\n" +
                        " |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")\n" +
                        " |> limit(n: %d, offset: %d)\n" +
                        " |> yield(name: \"mean\")",
                bucket, startTime, endTime, filterBuilder, pageSize, (pageNumber - 1) * pageSize
        );
    }

    private static String resolveTopic(String topic) {
        if (!"$event/close".equals(topic) || !"$event/connect".equals(topic)) {
            return "/iot/" + topic + "/realtimeData";
        }
        return null;
    }
}
